package com.fyl.leetcode.binarySearch;

/**
 * @author:fyl
 * @date 2021/8/25 18:47
 * @Modified By:
 * @Modified Date:
 * @Description: 704
 *
给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
示例 1:

输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
 */
public class Search {
//    左闭右闭区间
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        while (left <= right) {
            int index = (left + right) / 2;
            if (nums[index] < target) {
                left = ++index;
            } else if (nums[index] > target) {
                right = --index;
            } else {
                return index;
            }
        }
        return -1;
    }

//    左闭右开区间
    public int search1(int[] nums, int target) {
        int left = 0, right = nums.length;
        while (left < right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target)
                return mid;
            else if (nums[mid] < target)
                left = mid + 1;
            else if (nums[mid] > target)
                right = mid;
        }
        return -1;
    }
}
